<?php
# Basic RATS job flow test.
# Uses the RATS PHP Client to upload a src file, create a transcoding job for it, wait for the job to finish and process the results.
# Note that this is made to be run from cmd line, and only for demo purposes. In a live environment, you will need to improve things like I/O buffering, exception handling...
#
# Copyright (C) 2008 rambla.be
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require_once '../RawsClient/Raws/Rats.php';
# transient states -> processing not complete
define("REQUEST_RECEIVED", 1);
define("IMPORT_IN_PROGRESS", 2);
define("IMPORT_SUCCEEDED", 3);
define("TRANS_IN_PROGRESS", 4);
define("TRANS_SUCCEEDED", 5);
define("EXPORT_IN_PROGRESS", 6);
# final states
define("FINISHED", 7);
define("IMPORT_FAILED", 8);
define("TRANS_FAILED", 9);
define("EXPORT_FAILED", 10);
# fixed data
define('BASE', 'http://rats.enc01.rambla.be/');
define('SRC_FILENAME', 'test_one_srcfile.mp4'); # src_location
define('TGT_FILENAME', 'test_one'); # tgt_location

# Provide your own credentials here
define('USER', 'xxx');
define('PWD', 'xxx');
# provide a path to your local file to be used as transcoding src
define('LOCAL_FILE', '../test_resources/bla.mp4');
# you should specify your transcoding format ID here
define('FORMAT_PROFILE', ''); # E.g. "17"
# you should specify your output profile ID here
define('OUTPUT_PROFILE', ''); # E.g. "10"

try {
  # Create a Rass instance, passing it your login credentials and the base service uri
  $rats = new Rats(USER, PWD, BASE);

  # upload the src file, creating an "src" instance
  $src_entry = $rats->createSrc(SRC_FILENAME, LOCAL_FILE);
  $src_location = $src_entry->id->text; # uri to this src instance
  $src_filename = $src_entry->content->params->filename->text; # filename for this src on the RATS svr
  echo "\nUploaded a src file: \n";
  echo "src location: $src_location\n";

  # create a job, using the filename of the "src" file and a fixed format + output profile
  $rats = new Rats(USER, PWD, BASE);
  # NOTE: always use the src_filename from the src entry (returned by RATS when the src is created) 
  #       since RATS may have modified the original src filename (if a file with the same name already exists)
  $job_entry = $rats->createJobForExistingSrc(OUTPUT_PROFILE, FORMAT_PROFILE, $src_entry->content->params->filename->text, TGT_FILENAME, "40%", null, 50, null);

  $job_location = $job_entry->id->text; # uri to this job instance
  $job_id = $job_entry->content->params->id->text; # id for this job on the RATS svr
  echo "\nCreated a job: \n";
  echo "job location: $job_location\n";
  
  echo "\nWaiting for the job to be done: \n";
  # run a loop, polling the created job until it is finished
  while (1) {
    # retrieve the job entry
    $rats = new Rats(USER, PWD, BASE);
    $job_entry = $rats->getJobEntry($job_location);
    echo "Polling job " . $job_entry->content->params->id->text . ". Status= " . $job_entry->content->params->status->text . "\n";
    $status = (int)$job_entry->content->params->status->text; # current status
    # check on the status
    if ($status >= FINISHED) {
      if ($status == FINISHED) {
        echo "Job has succeeded, trying to retrieve the public URI for the exported file...\n";
        # retrieve the URI by which the transcoded file is available on the Rambla CDN
        $xml_entry =  $job_entry->getXML(); # get the complete entry in xml format
        $sxml_entry = simplexml_load_string($xml_entry);
        # parse the xml, looking for <public_uri> element inside <entry><reports><report><job action="export">
        foreach ($sxml_entry->children('http://rambla.be/raws/ns-metadata/1.0') as $reports) {
          foreach($reports->report->job as $job) {
            if ($job->attributes()->action[0] == "export") {
              echo "File on the CDN is accessible via URI: " . $job->public_uri[0] . "\n";
            }
          }
        }
        break;  
      }
      else {
        echo "Job has failed with status code = " . $job_entry->content->params->status->text . "\n";
        break;
      }
    }    
    sleep(20);
  }
  
  # (optional) src not longer needed on the RATS server, delete it
  $rats = new Rats(USER, PWD, BASE);
  $rats->deleteSrcFromFilename($src_filename);
  echo "\nSrc file has been deleted from the RATS server.";

}
catch(Zend_Gdata_App_Exception $e) {
    # Report the exception to the user
    echo "\nCaught exception: " . get_class($e) . "\n";
    echo "Message: " . $e->getMessage() . "\n";
    # get the HTTP status code
    echo "HTTP Status Code: " . $e->getResponse()->getStatus() . "\n";
    echo "Response Body with exception details: " . $e->getResponse()->getBody() . "\n";
    # get the raws:error elements
    $rawsResponse = Raws::parseRawsResponse($e->getResponse());
    echo "Raws Code: " . $rawsResponse->getCode() . "\n";
    echo "Raws Message: " . $rawsResponse->getMsg() . "\n";
    $reasons = $rawsResponse->getReasons();
    foreach ($reasons as $reason) {
      echo "Raws Reason: " . $reason . "\n";
    }
    $details = $rawsResponse->getDetails();
    foreach ($details as $key => $value) {
      echo "Raws Detail: " . $key . " -> " . $value . "\n";
    }
}
catch (Zend_Exception $e) {
    echo "Caught exception: " . get_class($e) . "\n";
    echo "Message: " . $e->getMessage() . "\n";
}